package com.xiangwei.controller;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.xiangwei.entity.Admin;
import com.xiangwei.entity.Template;
import com.xiangwei.service.IAdminService;
import com.xiangwei.service.ITemplateService;
import com.xiangwei.util.Common;
import com.xiangwei.util.DateUtils;
import com.xiangwei.util.QiniuUtil;
import com.xiangwei.util.StringUtils;



@Controller
@RequestMapping(value = "admin")
public class TempManageController {
	private final Logger logger = LoggerFactory.getLogger(TempManageController.class);
	
	@Autowired
	private ITemplateService templateService;
	@Autowired
	private IAdminService adminService;
	
	/**
     * 跳转模版列表页面
     * @return
     */
    @RequestMapping(value = "templateList", method = RequestMethod.GET)
    public String customerList(Model model) {
    	//初始化信息取得
    	List<Template> templateList = templateService.selectTemplateList();
    	model.addAttribute("templateList", templateList);
    	model.addAttribute("imageUrl", QiniuUtil.IMAGEURL);
        return "admin/templateList";//模版列表页面
    }
    
    /**
     * 新增模版页面
     * @return
     */
    @RequestMapping(value = "insertTemplate", method = RequestMethod.POST)
    public String insertTemplate(Template template ,Model model,HttpSession session) {
    	Admin ad = (Admin) session.getAttribute("admin");
    	if(ad.getRole() != 2){
    		logger.error("权限不足");
    		return "admin/templateList";
    	}
    	//初始化信息取得
    	templateService.insertTemplate(template);
        return "admin/templateList";//模版列表页面
    }
    
    /**
     * 验证是否有重复模版代码
     * @param vendorId
     * @param response
     */
    @RequestMapping(value = "checkTemplateCode", method = RequestMethod.POST)
    public void checkTemplateCode(String id, String templateCode, HttpServletResponse response){
    	Map<String, Object> map = new HashMap<String, Object>();
    	if(StringUtils.isEqual("0", id)){
    		id = null;
    	}
    	map.put("id",id);
    	map.put("templateCode", Integer.parseInt(templateCode));
    	int count = templateService.checkTemplateCode(map);
    	if(count == 0){
    		try {
    			response.getWriter().print("success");
    		} catch (IOException e) {
    			logger.error(e.getMessage(), e);
    			e.printStackTrace();
    		}
    	}
    }
    
	/**
	 *模版保存
	 * @param admin
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "saveTemplate", method = RequestMethod.POST)
	public String saveTemplate(@RequestParam("file") MultipartFile file,Template template, Model model,HttpServletRequest request) throws IOException {
    	HttpSession session = request.getSession();
    	Admin admin = (Admin) session.getAttribute("admin");
		if(Common.isNullOrEmpty(admin) || admin.getRole() != 2){
    		return "redirect:templateList";
    	}
		if(!file.isEmpty()){
    		// 文件保存路径  
    		String fileName = DateUtils.getCurrentDateString()+file.getOriginalFilename();      //文件名称
            String filePath = request.getSession().getServletContext().getRealPath("/") + "uploadImage/"  
                    + fileName;  
            // 如果不存在，则创建目录
            if (!new File(filePath).isDirectory()){
            	new File(filePath).mkdirs();
            }
            try {
            	// 转存文件
            	File fileSave = new File(filePath);
				file.transferTo(fileSave);
				template.setTemplateImg(fileName);
				String success = QiniuUtil.upload(filePath, fileName);         //上传到七牛云服务
            	if(success!=null){
            		fileSave.delete();          //如果上传成功，就删除本地服务的图片
            	}
			} catch (IllegalStateException e) {
				logger.error(e.getMessage(), e);
				throw new IllegalStateException("文件上传失败");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new IOException("文件上传失败");
			} 
    	}
		int count = templateService.saveTemplate(template);
		if(count >0){
			logger.info("保存成功");
		}else{
			logger.info("保存失败");
		}
		return "redirect:templateList";
	}
	
	/**
	 * 删除选中记录的模版信息
	 * @param id
	 * @param response
	 */
	@RequestMapping(value = "deleteTemplate", method = RequestMethod.POST)
	public void deleteTemplate(String id,HttpServletResponse response,HttpSession session){
		String msg = "fail";
    	Admin admin = (Admin) session.getAttribute("admin");
		if(Common.isNullOrEmpty(admin) || admin.getRole() != 2){
			try {
				response.getWriter().print(msg);
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
    		return;
    	}
		
		int count = templateService.deleteTemplateById(id);
		if(count >0){
			msg = "success";
		}
		try {
			response.getWriter().print(msg);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		
		
	}
	
	/**
	 * 查询出选中记录的模版信息
	 * @param id
	 * @param response
	 */
	@RequestMapping(value = "selectTemplateInfo", method = RequestMethod.POST)
	public void selectTemplateInfo(String id,HttpServletResponse response){
		Template template = templateService.selectTemplateInfo(id);
		if(template != null){
			try {
				List<Object> listData = new ArrayList<Object>();
				listData.add(template);
				//图片地址
				String imageUrl = QiniuUtil.IMAGEURL;
				listData.add(imageUrl);
				String json = JSONObject.toJSONString(listData);
    			response.getWriter().print(json);
    		} catch (IOException e) {
    			logger.error(e.getMessage(), e);
    			e.printStackTrace();
    		}
		}
	}
	
	@RequestMapping(value = "showHtml", method = RequestMethod.POST)
	public void showHtml(String id,HttpServletRequest request,HttpServletResponse response){
		if(!Common.isEmptyString(id)){
			return ;
		}
		Integer code = templateService.getHtml(id);
		if(Common.isNullOrEmpty(code)){
			return;
		}
		String basePath = "/view/template/portal_"+code+"/index.html";
		String filepath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()
				+request.getContextPath()+basePath;
		try {
			response.getWriter().print(filepath);				
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}
	
}
